package com.feihong.yw189.http;

import android.text.TextUtils;
import android.util.Log;

import com.feihong.yw189.app.App;
import com.feihong.yw189.utils.MyLoginUtils;
import com.feihong.yw189.utils.UserLoginInfo;

import org.json.JSONObject;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.x;

import static com.feihong.yw189.http.Host.HTTP_HOME;

/**
 * @author wangziheng
 * @name txgw_app
 * @class name：com.feihong.txgw.http
 * @class describe:
 * @time 2017/9/13 11:26
 * @change
 * @chang time
 * @class describe
 */
public class RefreshToken {

    public static final String QUERY_TOKEN_SUCCESS_CODE = "1";
    public static final String TOKEN_ERROR_REFRESH_CODE_KEY = "401";
    public static final String TOKEN_ERROR_LOGIN_CODE_KEY = "400";
    public static final String QUERY_TOKEN_SUCCESS_CODE_KEY = "status";
    private static final String QUERY_TOKEN_SUCCESS_DATA_KEY = "data";
    private static final String QUERY_TOKEN_SUCCESS_TOKEN_KEY = "token";

    private static class SingletonHolder {
        public static RefreshToken instance = new RefreshToken();
    }

    public static RefreshToken getInstance() {
        return SingletonHolder.instance;
    }

    private RefreshToken() {
    }

    /**
     * @param token 新token
     * @return
     */
    @Deprecated
    public synchronized boolean RefreshToken(String token) {

        if (!TextUtils.isEmpty(token) && !token.equals(UserLoginInfo.getUserLoginInfoInstance().getUserToken())) {
            App.getApp().lastUpdateToken = System.currentTimeMillis();
            return UserLoginInfo.getUserLoginInfoInstance().updateUserToken(token);
        } else if (!TextUtils.isEmpty(token) && token.equals(UserLoginInfo.getUserLoginInfoInstance().getUserToken())) {
            return true;
        }
        return false;
    }

    /**
     * post请求获取新token
     *
     * @return
     */
    public synchronized boolean postRequestGetToken() {
        return queryNewToken();
    }

    /**
     * get请求获取新token
     *
     * @return
     */
    public synchronized boolean getRequestGetToken() {
        return queryNewToken();
    }

    /**
     * 获取新token
     *
     * @return
     */
    private boolean queryNewToken() {

        long timeSpan = (System.currentTimeMillis() - App.getApp().lastUpdateToken);
        if (App.getApp().lastUpdateToken != 0 && timeSpan < 1000 * 9) {
            return true;
        }
        try {
            String usrAccount = App.getApp().getUserAccount();
            String userPassword = App.getApp().getUserPassword();
            RequestParams requestParams = new RequestParams(HTTP_HOME + "/DxApp/Login/login.html");
            long time = MyLoginUtils.getCuurrentTime();
            requestParams.addBodyParameter("time", String.valueOf(time));

            MyLoginUtils loginUtils = new MyLoginUtils(App.getApp().getApplication());

            String version = loginUtils.getVersion();
            String phone_os = loginUtils.getPhone_os();
            String phone_type = loginUtils.getPhone_type();
            String phone_brand = loginUtils.getPhone_brand();
            String phone_imei = loginUtils.getPhone_imei();
            String phone_gps = loginUtils.getPhone_gps();
            String Network = loginUtils.getNetwork();
            String Phone_num = loginUtils.getPhone_num();
            String locLon = UserLoginInfo.getUserLoginInfoInstance().getUserLoc().getUserLon();
            String locLat = UserLoginInfo.getUserLoginInfoInstance().getUserLoc().getUserLat();
            String locationLon = TextUtils.isEmpty(locLon) ? "" : locLon;
            String locationLat = TextUtils.isEmpty(locLat) ? "" : locLat;
            requestParams.addBodyParameter("long",locationLon);
            requestParams.addBodyParameter("lat",locationLat);
            requestParams.addBodyParameter("name", usrAccount);
            requestParams.addBodyParameter("network", Network);
            requestParams.addBodyParameter("password", userPassword);
            requestParams.addBodyParameter("phone_brand", phone_brand);
            requestParams.addBodyParameter("phone_gps", phone_gps);
            requestParams.addBodyParameter("phone_imei", phone_imei);
            requestParams.addBodyParameter("phone_num", Phone_num);
            requestParams.addBodyParameter("phone_os", phone_os);
            requestParams.addBodyParameter("phone_type", phone_type);
            requestParams.addBodyParameter("time", String.valueOf(time));
            requestParams.addBodyParameter("version", "and." + version);


            requestParams.setCacheMaxAge(0);
            requestParams.setMaxRetryCount(3);
            requestParams.setReadTimeout(15000);
            requestParams.setConnectTimeout(15000);
            requestParams.setMethod(HttpMethod.POST);
            String tokenResult = null;
            try {
                tokenResult = x.http().postSync(requestParams, String.class);
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
            if (!TextUtils.isEmpty(tokenResult)) {
                JSONObject jsonObject = new JSONObject(tokenResult);
                if (QUERY_TOKEN_SUCCESS_CODE.equals(jsonObject.optString(QUERY_TOKEN_SUCCESS_CODE_KEY))) {
                    App.getApp().lastUpdateToken = System.currentTimeMillis();
                    JSONObject tokenObj = jsonObject.optJSONObject(QUERY_TOKEN_SUCCESS_DATA_KEY);
                    String token = tokenObj.optString(QUERY_TOKEN_SUCCESS_TOKEN_KEY);
                    return UserLoginInfo.getUserLoginInfoInstance().updateUserToken(token);
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } catch (Exception throwable) {
            throwable.printStackTrace();
            return false;
        }
    }

    /**
     * 清除token
     */
    public void clearToken() {
        synchronized (this) {
            UserLoginInfo.getUserLoginInfoInstance().updateUserToken("");
        }
    }

}
